import { Component, createSignal, onMount } from 'solid-js';
import { useParams } from '@solidjs/router';
import { useAppDetailStore } from './store';
import './AppDetail.css';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import ScreenshotCarousel from '@/components/ScreenshotCarousel';
import { generateShareLinks, copy } from '@/lib/share';
import { showToast } from "@/components/ui/toast";
import { useCollectionStore } from '@/features/collection/store';
import { useDownloadsStore } from '@/features/downloads/store';
import { Progress } from '@/components/ui/progress';
import { X } from 'lucide-solid';
import { checkIsInstalled, checkLaunchApp, launchLaunchApp } from '@/lib/api/deb';

const AppDetail: Component = () => {
  const params = useParams();
  const { app, loading } = useAppDetailStore(params.category, params.pkgname);
  const { collections, addCollection, addAppToCollections, removeAppFromCollection, isAppInCollection } = useCollectionStore();
  const { downloads, addDownload, cancelDownload } = useDownloadsStore();
  const [newCollectionName, setNewCollectionName] = createSignal('');
  const [newCollectionDesc, setNewCollectionDesc] = createSignal('');
  const [showNewCollectionDialog, setShowNewCollectionDialog] = createSignal(false);
  const [showCollectionDialog, setShowCollectionDialog] = createSignal(false);
  const [isInstalled, setIsInstalled] = createSignal(false);
  const [selectedCollections, setSelectedCollections] = createSignal<string[]>([]);

  const handleCreateCollection = () => {
    if (!newCollectionName()) {
      showToast({ description: '请输入收藏单名称', variant: "warning" });
      return;
    }
    const newCollection = addCollection({
      name: newCollectionName(),
      description: newCollectionDesc(),
    });
    // 直接将当前应用添加到新创建的收藏单中
    addAppToCollections([newCollection.id], params.category, params.pkgname);
    setNewCollectionName('');
    setNewCollectionDesc('');
    setShowNewCollectionDialog(false);
    showToast({ description: '收藏单创建成功', variant: "success" });
  };

  onMount(async () => {
    const installed = await checkIsInstalled(params.pkgname);
    setIsInstalled(installed);
  });

  return (
    <div class="w-full h-full">
      {loading() ? (
        <div class="app-detail">
          <div class="info-container">
            <div class="app-title-container">
              <div class="flex-row-start gap-20px">
                <div class="app-icon bg-muted flex items-center justify-center overflow-hidden">
                  <Skeleton width={64} height={64} radius={8} />
                </div>
                <div class="py-2" />
                <Skeleton height={32} width={200} />
              </div>
              <div class="flex flex-col gap-2  w-[120px]">
                <Skeleton height={40} width={120} radius={6} />
                <Skeleton height={40} width={120} radius={6} />
                <Skeleton height={40} width={120} radius={6} />
              </div>
            </div>
            <div class="mt-2">
              <div class="py-2">
                <Skeleton height={24} width={80} class="mb-2" />
                <Skeleton height={16} width={100} class="mt-2" />
              </div>
              <div class="py-2">
                <Skeleton height={24} width={80} class="mb-2" />
                <div class="social-container text-sm text-muted-foreground">
                  <Skeleton height={16} width={120} />
                  <div class="divider" />
                  <Skeleton height={16} width={120} />
                  <div class="divider" />
                  <Skeleton height={16} width={120} />
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div class="app-detail">
          <div class="bg-container">
            <div
              class="bg"
              style={{
                'background-image': `url(${app()?.Icon})`,
                'background-size': 'cover',
                'background-position': 'center',
              }}
            />
          </div>
          <div class="info-container">
            <div class="app-title-container">
              <div class="flex-row-start gap-20px">
                <div class="app-icon bg-muted flex items-center justify-center overflow-hidden">
                  {app()?.Icon ? (
                    <img src={app()?.Icon} alt={app()?.Name} class="w-full h-full object-cover" />
                  ) : (
                    <div class="text-2xl font-bold text-muted-foreground">
                      {app()?.Name?.charAt(0)}
                    </div>
                  )}
                </div>
                <div class="py-2" />
                <h2 class="app-name text-2xl font-bold pt-2 select-text">{app()?.Name}</h2>
              </div>
              <div class="flex flex-col gap-2 w-[120px]">
                {(() => {
                  const downloadTask = downloads().find(task => 
                    task.category === params.category && 
                    task.pkgname === params.pkgname
                  );

                  if (downloadTask?.status === 'installed' || isInstalled()) {
                    const [appCanLaunch, setAppCanLaunch] = createSignal(false);
                    checkLaunchApp(params.pkgname).then(canLaunch => {
                      setAppCanLaunch(canLaunch);
                    });

                    return (
                      <Button 
                        size="lg" 
                        class='w-full'
                        disabled={!appCanLaunch()}
                        onClick={() => {
                          launchLaunchApp(params.pkgname)
                          showToast({ description: '正在启动应用...' });
                        }}
                      >
                        启动
                      </Button>
                    );
                  }

                  if (downloadTask) {
                    return (
                      <div class="flex flex-col gap-2 w-full pb-2">
                        <div class="flex items-center gap-2 group relative">
                          <Progress value={downloadTask.progress} class="flex-1" />
                          <div class="flex items-center gap-2 group-hover:opacity-0 transition-opacity">
                            <span class="text-sm text-muted-foreground">{downloadTask.progress}%</span>
                            {downloadTask.speed && (
                              <span class="text-sm text-muted-foreground">{downloadTask.speed}</span>
                            )}
                          </div>
                          <button 
                            class="absolute right-1 bg-red-500 rounded-full w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white hover:bg-red-600"
                            onClick={() => {
                              cancelDownload(params.category, params.pkgname);
                            }}
                          >
                            <X />
                          </button>
                        </div>
                      </div>
                    );
                  }

                  return (
                    <Button 
                      size="lg" 
                      class='w-full'
                      onClick={() => {
                        const currentApp = app();
                        if (!currentApp) {
                          showToast({ description: '获取应用信息失败', variant: "error" });
                          return;
                        }
                        
                        if (!currentApp.Filename) {
                          showToast({ description: '获取应用下载信息失败', variant: "error" });
                          return;
                        }
                        
                        addDownload(params.category, params.pkgname, currentApp.Filename, currentApp.Name || '');
                        showToast({ description: '已添加到下载队列', variant: "success" });
                      }}
                    >
                      安装
                    </Button>
                  );
                })()}
                <Dialog open={showCollectionDialog()} onOpenChange={setShowCollectionDialog}>
                  <DialogTrigger>
                    <Button variant="secondary" size="lg" class='w-full'>收藏</Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>添加到收藏单</DialogTitle>
                    </DialogHeader>
                    <div class="flex flex-col gap-4">
                      {collections().map(collection => (
                        <div class="flex items-center space-x-2">
                          <Checkbox
                            id={`collection-${collection.id}`}
                            checked={isAppInCollection(collection.id, params.category, params.pkgname)}
                            onChange={(checked) => {
                              if (checked) {
                                addAppToCollections([collection.id], params.category, params.pkgname);
                              } else {
                                removeAppFromCollection(collection.id, params.category, params.pkgname);
                              }
                            }}
                          />
                          <Label for={`collection-${collection.id}-input`}>{collection.name}</Label>
                        </div>
                      ))}
                      <Button variant="secondary" onClick={() => setShowNewCollectionDialog(true)}>创建新收藏单</Button>
                      <Button onClick={() => {
                        const selected = selectedCollections();
                        addAppToCollections(selected, params.category, params.pkgname);
                        showToast({ description: '添加到收藏单成功', variant: "success" });
                        setSelectedCollections([]);
                        setShowCollectionDialog(false);
                      }}>确认</Button>
                    </div>
                  </DialogContent>
                </Dialog>
                <DropdownMenu>
                  <DropdownMenuTrigger>
                    <Button variant="secondary" size="lg" class='w-full'>分享</Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent>
                    <DropdownMenuLabel>分享应用</DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onSelect={async () => {
                      try {
                        const links = await generateShareLinks(params.category, params.pkgname);
                        await copy(links.spkLink);
                        showToast({ description: 'SPK链接已复制到剪贴板', variant: "success" });
                      } catch (error) {
                        showToast({ description: '复制SPK链接失败', variant: "error" });
                      }
                    }}>复制SPK链接</DropdownMenuItem>
                    <DropdownMenuItem onSelect={async () => {
                      try {
                        const links = await generateShareLinks(params.category, params.pkgname);
                        await copy(links.shareLink);
                        showToast({ description: '分享链接已复制到剪贴板', variant: "success" });
                      } catch (error) {
                        showToast({ description: '复制分享链接失败', variant: "error" });
                      }
                    }}>复制分享链接</DropdownMenuItem>
                    <DropdownMenuItem onSelect={async () => {
                      try {
                        const links = await generateShareLinks(params.category, params.pkgname);
                        await copy(links.shareIframe);
                        showToast({ description: '嵌入代码已复制到剪贴板', variant: "success" });
                      } catch (error) {
                        showToast({ description: '复制嵌入代码失败', variant: "error" });
                      }
                    }}>复制嵌入代码</DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>
            <div class="mt-2 w-full">
              <div class="py-2">
                <h3 class="text-lg font-semibold">应用描述</h3>
                <p class="description text-muted-foreground select-text">{app()?.More}</p>
              </div>
              <div class="py-2">
                <h3 class="text-lg font-semibold">应用信息</h3>
                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 mt-2 text-sm text-muted-foreground">
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">软件大小</span>
                    <span class='select-text'>{app()?.Size}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">下载总量</span>
                    <span class='select-text'>{app()?.DownloadTimes}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">软件分类</span>
                    <span class='select-text'>{app()?.Category}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">软件包名</span>
                    <span class='select-text'>{app()?.Pkgname}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">更新时间</span>
                    <span class='select-text'>{app()?.Update}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">软件作者</span>
                    <span class='select-text'>{app()?.Author}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">投稿用户</span>
                    <span class='select-text'>{app()?.Contributor}</span>
                  </div>
                  <div class="flex flex-col">
                    <span class="text-xs text-muted-foreground mb-1">软件官网</span>
                    <a href={app()?.Website} target="_blank" rel="noopener noreferrer" class="text-blue-500 underline">点击跳转</a>
                  </div>
                </div>
              </div>
              <div class="py-2 w-full">
                <h3 class="text-lg font-semibold">应用截图</h3>
                <ScreenshotCarousel
                  screenshots={app()?.Screenshots?.map(url => ({
                    url,
                    title: app()?.Name || ''
                  }))}
                  loading={loading()}
                />
              </div>
            </div>
          </div>
        </div>
      )}
      <Dialog open={showNewCollectionDialog()} onOpenChange={setShowNewCollectionDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>创建新收藏单</DialogTitle>
          </DialogHeader>
          <div class="flex flex-col gap-4">
            <div class="flex flex-col gap-2">
              <Label>名称</Label>
              <Input
                value={newCollectionName()}
                onInput={(e) => setNewCollectionName(e.currentTarget.value)}
                placeholder="请输入收藏单名称"
              />
            </div>
            <div class="flex flex-col gap-2">
              <Label>描述</Label>
              <Input
                value={newCollectionDesc()}
                onInput={(e) => setNewCollectionDesc(e.currentTarget.value)}
                placeholder="请输入收藏单描述（选填）"
              />
            </div>
            <Button onClick={handleCreateCollection}>创建</Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default AppDetail;